package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.Arrays;
import java.util.UUID;


@RestController
@Slf4j
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 上传文件
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上次：{}", file);

        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;
            String path1 = ResourceUtils.getURL("classpath:").getPath();
            String path2 = path1.replace("target/classes", "src/main/resources");
            String targetPath = path1 + "static/upload/";
            String srcPath = path2 + "static/upload/";
            InputStream inputStream1 = file.getInputStream();
            OutputStream outputStream1 = new FileOutputStream(srcPath + objectName);
            for(int c=0;(c=inputStream1.read())!=-1;){
                outputStream1.write(c);
            }
            InputStream inputStream2 = file.getInputStream();
            OutputStream outputStream2 = new FileOutputStream(targetPath+ objectName);
            for(int c=0;(c=inputStream2.read())!=-1;){
                outputStream2.write(c);
            }

            // file.transferTo(new File(srcPath, objectName));
            // file.transferTo(new File(targetPath, objectName));
            objectName = "http://localhost:8080/images/" + objectName;
            // aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(objectName);
        } catch (IOException e) {
            log.info("文件上传失败");
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
